from flask import jsonify
from flask_restful import Resource, fields, marshal_with, reqparse
from .models import *


# 类视图：CBV   Class Based View
# 视图函数：FBV  Function Based View

class HelloWorld(Resource):
    def get(self):
        return jsonify({'msg':'get请求'})
    def post(self):
        return jsonify({'msg': 'post请求'})


# ------------------------------ 字段格式化 ------------------------------
# Flask-RESTful
# 字段格式化：定义返回给前端的数据格式
ret_fields = {
    'status': fields.Integer,
    'msg':fields.String,
    'data1':fields.String(default='zhang'),
    'data2':fields.String(attribute='data')  #使用data的值
}
class UserResource(Resource):
    @marshal_with(ret_fields)
    def get(self):
        return {
            'status':1,
            'msg':'ok',
            'data':'20250715'
        }


# ------------------------------ 字段格式化 ------------------------------
# user对象
user_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'age': fields.Integer,
    # absolute=True  绝对路径
    'url': fields.Url(endpoint='id',absolute=True)
}


ret_fields2 = {
    'status': fields.Integer,
    'msg': fields.String,
    'data': fields.Nested(user_fields)
}


class UserResource2(Resource):
    @marshal_with(ret_fields2)
    def get(self):
        user = User.query.first()
        return {
            'status': 1,
            'msg': 'ok',
            'data': user
        }


# ------------------------------ 字段格式化 ------------------------------
user_fields3 = {
    'name': fields.String,
    'age': fields.Integer,
}

ret_fields3 = {
    'status': fields.Integer,
    'msg': fields.String,
    'data': fields.List(fields.Nested(user_fields3))
}


class UserResource3(Resource):
    @marshal_with(ret_fields3)
    def get(self):
        user = User.query.all()
        return {
            'status': 1,
            'msg': 'ok',
            'data': user
        }
# ------------------------------ 参数解析 ------------------------------
# 参数解析：解析前端发送过来的数据
# RequestParser  解析器
parser = reqparse.RequestParser()
parser.add_argument('name',type=str,required=True,help='name是必需的参数')
parser.add_argument('age',type=int,action='append')  # 可以有多个age
parser.add_argument('key',type=str,location='cookies')
class UserResource4(Resource):
    def get(self):
        # 获取参数
        args = parser.parse_args()
        name = args.get('name')
        age = args.get('age')
        key = args.get('key')
        BAIDUID = args.get('BAIDUID')
        return {'name': name,
                'age': age,
                'key':key
                }